﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Controls.Primitives;

namespace CodeCounsel.Office.DatabindingToolkit
{
    /// <summary>
    /// Interaction logic for WPFTaskPane.xaml
    /// </summary>
    public partial class WPFTaskPane : System.Windows.Controls.UserControl
    {
        public Document Document { get; private set; }
        TreeViewItem _previousSelectedNode = null;
        Popup dragPopup = null;

        public WPFTaskPane()
        {
            InitializeComponent();
            TextBlock b;
            
        }

        internal void SetDocument(Document document)
        {
            DataContext = document;
            Document = document;
        }

        private void insertXmlPartButton_Click(object sender, RoutedEventArgs e)
        {
            using (System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog())
            {
                dialog.Multiselect = true;
                dialog.Filter = "XML files|*.xml|All files|*.*";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foreach (string path in dialog.FileNames)
                    {
                        CustomXmlPart xmlPart = Document.XmlParts.Add(
                            File.ReadAllText(path));
                        if (customXmlPartsList.SelectedIndex == -1)
                        {
                            customXmlPartsList.SelectedItem = xmlPart;
                        }
                    }
                }
            }
        }

        private void CustomXmlTreeView_TreeViewItemSelected(object sender, RoutedEventArgs e)
        {
            // switch between selected and non-selected templates;
            TreeViewItem selectedNode = (TreeViewItem)e.OriginalSource;
            if (_previousSelectedNode != null)
            {
                HierarchicalDataTemplate normalTemplate = (HierarchicalDataTemplate)Resources["normalNode"];
                _previousSelectedNode.HeaderTemplate = normalTemplate;
            }
            HierarchicalDataTemplate selectedTemplate = (HierarchicalDataTemplate)Resources["selectedNode"];
            selectedNode.HeaderTemplate = selectedTemplate;
            _previousSelectedNode = selectedNode;
        }

        private void ShowControlTypeContextMenuButton_Click(object sender, RoutedEventArgs e)
        {
            // open context menu on left-click
            System.Windows.Controls.Button b = (System.Windows.Controls.Button)sender;
            b.ContextMenu.IsOpen = true;
        }

        private void ShowControlTypeContextMenu_MenuItemClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.MenuItem item =
                (System.Windows.Controls.MenuItem)e.OriginalSource;
            ControlType selectedType = (ControlType)item.DataContext;
            CustomXmlNode node = (CustomXmlNode)customXmlTreeView.SelectedItem;
            node.ProposedType = selectedType;
        }

        private void CustomXmlTreeViewNode_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            CustomXmlNode node = (CustomXmlNode)customXmlTreeView.SelectedItem;
            if (node.HasChildNodes == false)
            {
                ValueControl control = (ValueControl)node.ProposedType;
                string prefix =
                    String.IsNullOrEmpty(node.NamespaceUri) == false ?
                    String.Format("xmlns:{0}='{1}'",
                    node.Owner.LookupPrefix(node.NamespaceUri),
                    node.NamespaceUri) : "";
                string id = node.Owner.ID;
                id = id.Trim('{', '}');
                id = "X_" + id.ToUpper();
                string text = BuildControlString(node.XPath, node.Owner.ID, prefix,
                    control.WordType);
                System.Windows.DataObject d = new System.Windows.DataObject(
                    "HTML Format", text);

                ControlTemplate t = (ControlTemplate)FindResource("dragPopup");
                dragPopup = (Popup)t.LoadContent();
                dragPopup.DataContext = node;
                dragPopup.IsOpen = true;

                dragPopup.Placement = PlacementMode.Relative;
                dragPopup.PlacementTarget = (TextBlock)sender;
                DragDrop.DoDragDrop((TextBlock)sender, d, System.Windows.DragDropEffects.Copy);
                dragPopup.IsOpen = false;
                dragPopup = null;
            }
        }

        void CustomXmlTreeViewNode_GiveFeedback(object sender, System.Windows.GiveFeedbackEventArgs e)
        {
            System.Drawing.Point pos = System.Windows.Forms.Cursor.Position;
            TextBlock block = (TextBlock)sender;
            Point point2 = block.PointToScreen(new Point(0, 0));
            dragPopup.VerticalOffset = pos.Y - point2.Y + 10;
            dragPopup.HorizontalOffset = pos.X - point2.X + 10;
            e.UseDefaultCursors = true;
            e.Handled = true;
        }

        string BuildControlString(string xpath,
            string storeItemID, string prefix,
            Microsoft.Office.Interop.Word.WdContentControlType type)
        {
            int headerLength = 105;

            string htmlHeader = Environment.NewLine +
@"<html xmlns:o=""urn:schemas-microsoft-com:office:office""
xmlns:w=""urn:schemas-microsoft-com:office:word""
xmlns:m=""http://schemas.microsoft.com/office/2004/12/omml""
xmlns=""http://www.w3.org/TR/REC-html40"">
<body>";
            string htmlFooter = @"</body></html>";
            string fragment = null;

            switch (type)
            {
                case Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText:
                    fragment = String.Format(@"
<w:Sdt Text=""t"" Xpath=""{0}"" ShowingPlcHdr=""t"" StoreItemID=""{1}"" PrefixMappings=""{2}"">
<p>Enter a value</p>
</w:Sdt>", xpath, storeItemID, prefix);
                    break;
                case Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlComboBox:
                    fragment = String.Format(@"
<w:Sdt Combobox=""t"" Xpath=""{0}"" ShowingPlcHdr=""t"" StoreItemID=""{1}"" PrefixMappings=""{2}"">
<p>Enter a value</p>
</w:Sdt>", xpath, storeItemID, prefix);
                    break;
                case Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlDropdownList:
                    fragment = String.Format(@"
<w:Sdt DropDown=""t"" Xpath=""{0}"" ShowingPlcHdr=""t"" StoreItemID=""{1}"" PrefixMappings=""{2}"">
<p>Enter a value</p>
</w:Sdt>", xpath, storeItemID, prefix);
                    break;
                case Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlDate:
                    fragment = String.Format(@"
<w:Sdt Calendar=""t"" Xpath=""{0}"" ShowingPlcHdr=""t"" StoreItemID=""{1}"" PrefixMappings=""{2}"">
<p>Enter a value</p>
</w:Sdt>", xpath, storeItemID, prefix);
                    break;
            }

            int startFragment = headerLength + htmlHeader.Length;
            int endFragment = startFragment + fragment.Length;
            int endHtml = endFragment + htmlFooter.Length;
            string header =
                "Version:1.0" + Environment.NewLine +
                "StartHTML:" + headerLength.ToString("0000000000") + Environment.NewLine +
                "EndHTML:" + endHtml.ToString("0000000000") + Environment.NewLine +
                "StartFragment:" + startFragment.ToString("0000000000") + Environment.NewLine +
                "EndFragment:" + endFragment.ToString("0000000000") + Environment.NewLine;

            return String.Concat(
                header, htmlHeader, fragment, htmlFooter);
        }
    }
}

